<template>
  <div class="result-display">
    <h2 class="section-title">
      <span class="title-icon">📋</span>
      解码结果
    </h2>
    
    <div v-if="loading" class="loading-state">
      <a-spin size="large" />
      <p>正在解码中...</p>
    </div>
    
    <div v-else-if="result" class="result-content">
      <div class="result-header">
        <a-tag :color="getTypeColor(result.type)" class="type-tag">
          {{ getTypeName(result.type) }}
        </a-tag>
        <span class="decode-time">{{ formatTime(result.timestamp) }}</span>
      </div>
      
      <div class="result-body">
        <div class="content-display">
          <div class="content-label">解码内容:</div>
          <div class="content-value">
            <pre v-if="isLongContent">{{ result.content }}</pre>
            <span v-else>{{ result.content }}</span>
          </div>
        </div>
        
        <!-- 特殊类型的额外信息 -->
        <div v-if="parsedContent" class="parsed-content">
          <div class="content-label">解析信息:</div>
          <div class="parsed-info">
            <div v-for="(value, key) in parsedContent" :key="key" class="info-item">
              <span class="info-key">{{ key }}:</span>
              <span class="info-value">{{ value }}</span>
            </div>
          </div>
        </div>
        
        <div class="result-actions">
          <a-button @click="copyContent" type="primary">
            <template #icon>
              <CopyOutlined />
            </template>
            复制内容
          </a-button>
          
          <a-button 
            v-if="result.type === 'url'" 
            @click="openUrl" 
            type="default"
          >
            <template #icon>
              <LinkOutlined />
            </template>
            打开链接
          </a-button>
          
          <a-button 
            v-if="result.type === 'phone'" 
            @click="callPhone" 
            type="default"
          >
            <template #icon>
              <PhoneOutlined />
            </template>
            拨打电话
          </a-button>
          
          <a-button 
            v-if="result.type === 'email'" 
            @click="sendEmail" 
            type="default"
          >
            <template #icon>
              <MailOutlined />
            </template>
            发送邮件
          </a-button>
          
          <a-button 
            v-if="result.type === 'sms'" 
            @click="sendSms" 
            type="default"
          >
            <template #icon>
              <MessageOutlined />
            </template>
            发送短信
          </a-button>
        </div>
      </div>
      
      <!-- 二维码来源信息 -->
      <div class="source-info">
        <div class="source-item">
          <span class="source-label">解码方式:</span>
          <span class="source-value">
            {{ result.source === 'upload' ? '图片上传' : '摄像头扫描' }}
          </span>
        </div>
        <div class="source-item">
          <span class="source-label">解码时间:</span>
          <span class="source-value">{{ formatFullTime(result.timestamp) }}</span>
        </div>
      </div>
    </div>
    
    <div v-else class="empty-state">
      <div class="empty-icon">
        <QrcodeOutlined />
      </div>
      <h3 class="empty-title">等待解码</h3>
      <p class="empty-text">请上传图片或使用摄像头扫描二维码</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { message } from 'ant-design-vue'
import {
  CopyOutlined,
  LinkOutlined,
  PhoneOutlined,
  MailOutlined,
  MessageOutlined,
  QrcodeOutlined
} from '@ant-design/icons-vue'
import { DecodeResult, QrCodeType } from '../utils/qrDecoder'

// 定义属性
interface Props {
  result: DecodeResult | null
  loading: boolean
}

const props = defineProps<Props>()

// 计算属性
const isLongContent = computed(() => {
  return props.result && props.result.content.length > 100
})

const parsedContent = computed(() => {
  if (!props.result) return null
  
  const { type, content } = props.result
  
  switch (type) {
    case QrCodeType.WIFI:
      return parseWifiContent(content)
    case QrCodeType.VCARD:
      return parseVCardContent(content)
    case QrCodeType.URL:
      return parseUrlContent(content)
    default:
      return null
  }
})

// 获取类型颜色
const getTypeColor = (type: QrCodeType): string => {
  const colorMap = {
    [QrCodeType.URL]: 'blue',
    [QrCodeType.TEXT]: 'green',
    [QrCodeType.WIFI]: 'orange',
    [QrCodeType.VCARD]: 'purple',
    [QrCodeType.EMAIL]: 'cyan',
    [QrCodeType.PHONE]: 'magenta',
    [QrCodeType.SMS]: 'lime',
    [QrCodeType.UNKNOWN]: 'default'
  }
  return colorMap[type] || 'default'
}

// 获取类型名称
const getTypeName = (type: QrCodeType): string => {
  const nameMap = {
    [QrCodeType.URL]: '网址链接',
    [QrCodeType.TEXT]: '文本内容',
    [QrCodeType.WIFI]: 'WiFi信息',
    [QrCodeType.VCARD]: '联系人',
    [QrCodeType.EMAIL]: '邮箱地址',
    [QrCodeType.PHONE]: '电话号码',
    [QrCodeType.SMS]: '短信内容',
    [QrCodeType.UNKNOWN]: '未知类型'
  }
  return nameMap[type] || '未知类型'
}

// 格式化时间
const formatTime = (timestamp: number): string => {
  const now = Date.now()
  const diff = now - timestamp
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return new Date(timestamp).toLocaleDateString()
  }
}

// 格式化完整时间
const formatFullTime = (timestamp: number): string => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

// 解析WiFi内容
const parseWifiContent = (content: string) => {
  const match = content.match(/WIFI:T:([^;]*);S:([^;]*);P:([^;]*);H:([^;]*);?/)
  if (match) {
    return {
      '加密方式': match[1] || '无',
      '网络名称': match[2] || '',
      '密码': match[3] || '无密码',
      '隐藏网络': match[4] === 'true' ? '是' : '否'
    }
  }
  return null
}

// 解析vCard内容
const parseVCardContent = (content: string) => {
  const lines = content.split('\n')
  const parsed: Record<string, string> = {}
  
  lines.forEach(line => {
    if (line.startsWith('FN:')) {
      parsed['姓名'] = line.substring(3)
    } else if (line.startsWith('ORG:')) {
      parsed['组织'] = line.substring(4)
    } else if (line.startsWith('TEL:')) {
      parsed['电话'] = line.substring(4)
    } else if (line.startsWith('EMAIL:')) {
      parsed['邮箱'] = line.substring(6)
    }
  })
  
  return Object.keys(parsed).length > 0 ? parsed : null
}

// 解析URL内容
const parseUrlContent = (content: string) => {
  try {
    const url = new URL(content)
    return {
      '协议': url.protocol,
      '域名': url.hostname,
      '端口': url.port || '默认',
      '路径': url.pathname || '/',
      '参数': url.search || '无'
    }
  } catch {
    return null
  }
}

// 复制内容
const copyContent = async () => {
  if (!props.result) return
  
  try {
    await navigator.clipboard.writeText(props.result.content)
    message.success('内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    message.error('复制失败，请手动复制')
  }
}

// 打开链接
const openUrl = () => {
  if (!props.result || props.result.type !== QrCodeType.URL) return
  
  try {
    window.open(props.result.content, '_blank')
  } catch (error) {
    console.error('打开链接失败:', error)
    message.error('无法打开链接')
  }
}

// 拨打电话
const callPhone = () => {
  if (!props.result || props.result.type !== QrCodeType.PHONE) return
  
  const phoneNumber = props.result.content.replace(/^tel:/, '')
  window.location.href = `tel:${phoneNumber}`
}

// 发送邮件
const sendEmail = () => {
  if (!props.result || props.result.type !== QrCodeType.EMAIL) return
  
  const email = props.result.content.replace(/^mailto:/, '')
  window.location.href = `mailto:${email}`
}

// 发送短信
const sendSms = () => {
  if (!props.result || props.result.type !== QrCodeType.SMS) return
  
  const sms = props.result.content.replace(/^sms:/, '')
  window.location.href = `sms:${sms}`
}
</script>

<style scoped>
.result-display {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 20px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #1a1a1a;
}

.title-icon {
  font-size: 18px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  gap: 16px;
  color: #666;
}

.loading-state p {
  margin: 0;
  font-size: 14px;
}

.result-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.type-tag {
  font-weight: 500;
}

.decode-time {
  font-size: 12px;
  color: #8c8c8c;
}

.result-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.content-display,
.parsed-content {
  background: #fafafa;
  border-radius: 6px;
  padding: 12px;
  border: 1px solid #f0f0f0;
}

.content-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.content-value {
  word-break: break-all;
  line-height: 1.5;
}

.content-value pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: inherit;
  font-size: 14px;
  background: none;
  border: none;
  padding: 0;
}

.parsed-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.info-key {
  font-size: 12px;
  color: #666;
  font-weight: 500;
  min-width: 60px;
}

.info-value {
  font-size: 14px;
  color: #1a1a1a;
  font-weight: 500;
  text-align: right;
  word-break: break-all;
}

.result-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.result-actions .ant-btn {
  flex: 1;
  min-width: 120px;
}

.source-info {
  background: #f9f9f9;
  border-radius: 6px;
  padding: 12px;
  border: 1px solid #f0f0f0;
}

.source-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.source-item:not(:last-child) {
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 8px;
  padding-bottom: 8px;
}

.source-label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.source-value {
  font-size: 12px;
  color: #1a1a1a;
  font-weight: 500;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  text-align: center;
  color: #8c8c8c;
  gap: 16px;
}

.empty-icon {
  font-size: 64px;
  opacity: 0.5;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #1a1a1a;
}

.empty-text {
  font-size: 14px;
  margin: 0;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .result-actions .ant-btn {
    width: 100%;
    min-width: auto;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .info-value {
    text-align: left;
  }
}
</style>